import { message } from 'antd'
import axios from 'axios'
import { getToken } from '../utils/user-token'

const instance = axios.create({
    baseURL: 'http://localhost:3005/',
    // 接口超时上限 5s
    timeout: 5 * 1000,
    headers: {},
})

export default instance

// request 拦截器 [ 所有接口 | 每次发送的时候带上token ]
instance.interceptors.request.use(
    config => {
        config.headers['Authorization'] = `Bearer ${getToken()}` // JWT 固定格式
        return config
    },
    error => Promise.reject(error)
)

// response 拦截器， 统一处理 errno 和 msg
instance.interceptors.response.use(res => {
    const resData = (res.data || {}) as ResType
    const { errno, data, msg } = resData
    if (errno !== 0) {
        // 错误提示
        if (msg) {
            message.error(msg)
        }
        throw new Error(msg) // 在控制台报错
    }
    return data as any
})

// 接口response的结构
export type ResType = {
    errno: number
    data?: ResDataType
    msg?: any
}

export type ResDataType = {
    [key: string]: any
}
